#pragma once
#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <functional>
#include "Logger.hpp"

using func_t = std::function<std::string(const std::string &world)>;

const static int initfd = -1;

class Server
{
public:
    Server(uint16_t port, func_t cb)
        : _socketfd(initfd), _port(port), _isrunning(false), _cb(cb)
    {
    }
    void Init()
    {
        _socketfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_socketfd < 0)
        {
            LOG(LogLevel::FATAL) << "创建socket失败";
            exit(1);
        }
        LOG(LogLevel::INFO) << "创建socket成功";
        struct sockaddr_in local;

        socklen_t len = sizeof(local);
        bzero(&local,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        int n = bind(_socketfd, (struct sockaddr *)&local, len);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind失败";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind成功";
    }
    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024];
            buffer[0] = 0;
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int n = recvfrom(_socketfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                buffer[n] = 0;
                std::string world = buffer;
                LOG(LogLevel::INFO) << "用户查询：" << world;
                std::string Result = _cb(world);
                sendto(_socketfd, Result.c_str(), Result.size(), 0, (struct sockaddr *)&peer, sizeof(sockaddr));
            }
            else
            {
                LOG(LogLevel::FATAL) << "读取失败";
                exit(3);
            }
        }
        _isrunning = false;
    }
    void Stop()
    {
    }
    ~Server() {}

private:
    int _socketfd;
    uint16_t _port;
    bool _isrunning;
    func_t _cb;
};